# 在代理端口限制的情况下，如：协助代理应用如nginx，使用80代理443的单个请求访问。
from flask import Flask, request
import requests

app = Flask(__name__)

@app.route('/<path:subpath>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def proxy(subpath):
    domain = request.headers.get('Host')  # 获取访问的域名
    print(request)
    print(domain)
    if domain == 'www.baidu.com':
        target_url = f'https://www.baidu.com/{subpath}'
    elif domain == 'www.ready.noaa.gov':
        target_url = f'https://www.ready.noaa.gov/{subpath}'
    else:
        return 'Domain not supported', 400

    response = requests.request(
        method=request.method,
        url=target_url,
        headers={key: value for (key, value) in request.headers if key != 'Host'},
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False,
        verify=False
    )

    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    headers = [(name, value) for (name, value) in response.raw.headers.items() if name.lower() not in excluded_headers]

    return response.content, response.status_code, headers

if __name__ == '__main__':
    app.run()
